<template>
  <div class="image-upload-container">
    <!-- 图片展示区域 -->
    <div class="image-display-area">
      <!-- 已上传的图片 -->
      <!-- <div class="image-list">
        <div v-for="(image, index) in images" :key="index" class="image-item">
          <img :src="image.url" :alt="`图片${index + 1}`" />
          <div class="image-overlay" @click="removeImage(index)">
            <div class="delete-icon" v-if="activeName_1 == '1'">×</div>
          </div>
        </div>
      </div> -->

      <!-- 上传图片按钮 -->
      <div class="upload-button-container" v-if="activeName_1 == '1'">
        <el-dropdown @command="handleCommand" placement="bottom-start">
          <div type="primary" class="upload-btn">
            <img src="@/assets/manage/icon_photo_nor.svg" alt="" />
            上传图片
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="upload"> 上传图片 </el-dropdown-item>
              <!-- <el-dropdown-item command="camera"> 摄像头拍摄 </el-dropdown-item>
              <el-dropdown-item command="scanner"> 高拍仪拍摄 </el-dropdown-item> -->
              <el-dropdown-item command="scanner"> 拍摄 </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 隐藏的文件上传输入框 -->
    <input
      ref="fileInput"
      type="file"
      multiple
      accept="image/*"
      style="display: none"
      @change="handleFileUpload"
    />

    <!-- 摄像头拍摄弹框 -->
    <el-dialog
      v-model="cameraDialogVisible"
      title="摄像头拍摄"
      width="60%"
      :show-close="true"
      :close-on-click-modal="false"
      class="camera-dialog"
    >
      <div class="camera-container">
        <!-- 摄像头预览区域 -->
        <div class="camera-preview">
          <video
            ref="videoElement"
            autoplay
            playsinline
            muted
            class="camera-video"
          ></video>

          <!-- 拍摄画布（用于捕获图片） -->
          <canvas
            ref="canvasElement"
            class="camera-canvas"
            style="display: none"
          ></canvas>
        </div>
      </div>

      <!-- 拍摄按钮 -->
      <template #footer>
        <div class="camera-footer">
          <el-button @click="closeCameraDialog">取消</el-button>
          <el-button type="primary" @click="capturePhoto" class="capture-btn">
            拍摄
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 高拍仪拍摄弹框 -->
    <el-dialog
      v-model="scannerDialogVisible"
      title="高拍仪拍摄"
      width="60%"
      :show-close="true"
      :close-on-click-modal="false"
      class="scanner-dialog"
      @close="handleScannerDialogClose"
    >
      <div class="scanner-container">
        <!-- 高拍仪预览区域 -->
        <div class="scanner-preview" v-loading="!scannerVideoUrl">
          <img
            v-if="scannerVideoUrl"
            :key="scannerVideoUrl"
            ref="scannerVideoElement"
            :src="scannerVideoUrl"
            alt="高拍仪预览"
            class="scanner-video"
          />
          <div v-if="!scannerVideoUrl" class="loading-overlay">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在连接高拍仪...</p>
          </div>
        </div>
      </div>

      <!-- 拍摄按钮 -->
      <template #footer>
        <div class="scanner-footer">
          <el-button @click="closeScannerDialog">取消</el-button>
          <el-button
            type="primary"
            @click="captureWithScannerDialog"
            :loading="scannerCapturing"
            class="capture-btn"
          >
            {{ scannerCapturing ? '拍摄中...' : '拍摄' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { Upload, Camera, Close, Loading } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { uploadFile } from '@/api/basedata/index';
import { base64Upload } from '@/api/account';
import { getScannerInstance } from '@/utils/scanner';
interface ImageItem {
  url: string;
  file?: File;
  name: string;
}

const props = defineProps<{
  modelValue?: ImageItem[];
  fieldImages?: any;
  maxImages?: number;
  activeName_1?: string;
}>();

// const emit = defineEmits<{
//   'update:modelValue': [value: ImageItem[]];
//   change: [value: ImageItem[]];
//   (e: 'loadingFalse', isLoading: boolean, message: string): void
// }>();
const emit = defineEmits([
  'update:modelValue',
  'change',
  'loadingFalse',
]);

// 响应式数据
// 由 watcher 进行规范化填充
const images = ref<any[]>([]);
watch(
  () => props.fieldImages,
  (newVal) => {
    //console.log(newVal);
    // 规范化：如果不是数组，则按逗号分割为数组
    const raw = newVal as any;
    let list: any[] = [];
    if (Array.isArray(raw)) {
      list = raw;
    } else if (typeof raw === 'string') {
      list = raw
        .split(',')
        .map((s) => s.trim())
        .filter((s) => !!s);
    } else if (raw == null) {
      list = [];
    } else {
      // 其他类型直接清空，避免异常
      list = [];
    }

    if (list.length > 0) {
      images.value = list
        .map((item: any) => {
          if (typeof item === 'string') {
            const img: ImageItem = { url: item, name: '' };
            return img;
          }
          if (item && typeof item === 'object' && item.url) {
            const file: File | undefined =
              item.file instanceof File ? item.file : undefined;
            const img: ImageItem = {
              url: String(item.url),
              file,
              name: String(item.name ?? ''),
            };
            return img;
          }
          return null;
        })
        .filter(
          (x: any): x is ImageItem =>
            !!x && typeof x.url === 'string' && x.url.length > 0
        );
    } else {
      images.value = [];
    }
  },
  { immediate: true, deep: true }
);

// 摄像头相关状态
const cameraDialogVisible = ref(false);
const fileInput = ref<HTMLInputElement>();
const videoElement = ref<HTMLVideoElement>();
const canvasElement = ref<HTMLCanvasElement>();
const mediaStream = ref<MediaStream | null>(null);

// 高拍仪相关状态
const scannerDialogVisible = ref(false);
const scannerVideoElement = ref<HTMLImageElement>();
const scannerVideoUrl = ref('');
const scannerCapturing = ref(false);
const scannerConnectionStatus = ref<boolean | null>(null); // 缓存高拍仪连接状态: null=未检测, true=已连接, false=未连接

// 加载状态
const isLoadingCamera = ref(false); // 摄像头加载中
const isLoadingScanner = ref(false); // 高拍仪加载中

// 初始化高拍仪实例
// 在 HTTPS 环境下，如果高拍仪服务不支持 HTTPS，强制使用 HTTP
// 注意：浏览器可能会阻止混合内容，需要在浏览器设置中允许
const isHttpsEnv = typeof window !== 'undefined' && window.location.protocol === 'https:';
const scanner = getScannerInstance({ 
  // forceHttp: isHttpsEnv // HTTPS 环境下强制使用 HTTP，避免 WSS/HTTPS 连接问题
});

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  if (command === 'upload') {
    triggerFileUpload();
  } else if (command === 'camera') {
    openCameraDialog();
  } else if (command === 'scanner') {
    openSmartCaptureDialog();
  }
};

// 触发文件上传
const triggerFileUpload = () => {
  fileInput.value?.click();
};

// 处理文件上传
const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;

  if (!files) return;

  Array.from(files).forEach((file) => {
    if (props.maxImages && images.value.length >= props.maxImages) {
      ElMessage({
        message: `最多只能上传${props.maxImages}张图片`,
        type: 'warning',
        duration: 2000,
      });
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      const newImage: ImageItem = {
        url: e.target?.result as string,
        file: file,
        name: file.name,
      };
      uploadFile(file, file.name).then((res) => {
        if (res.data) {
          images.value.push({
            url: res.data,
            name: file.name,
            file: file,
          });
        }
        updateModelValue();
      });
    };
    reader.readAsDataURL(file);
  });

  // 重置input值，允许重复选择同一文件
  target.value = '';
};

// 移除图片
const removeImage = (index: number) => {
  images.value.splice(index, 1);
  updateModelValue();
};

/**
 * 打开摄像头对话框（等待图像真正加载后再显示弹窗）
 */
const openCameraDialog = async () => {
  let tempVideo: HTMLVideoElement | null = null;
  
  try {
     emit('loadingFalse', true, '正在启动摄像头...');
    // 显示加载提示
    isLoadingCamera.value = true;
    // const loadingMessage = ElMessage({
    //   message: '正在启动摄像头...',
    //   type: 'info',
    //   duration: 0,
    //   icon: Loading,
    // });
    
    // 先获取摄像头权限和流
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'user', // 前置摄像头，可改为 'environment' 使用后置摄像头
      },
    });
    
    mediaStream.value = stream;
    
    // 创建临时 video 元素来预加载视频流
    tempVideo = document.createElement('video');
    tempVideo.srcObject = stream;
    tempVideo.autoplay = true;
    tempVideo.muted = true;
    tempVideo.playsInline = true;
    
    // 等待视频流真正开始播放（图像加载完成）
    await new Promise<void>((resolve, reject) => {
      const timeout = setTimeout(() => {
        reject(new Error('摄像头加载超时'));
      }, 10000); // 10秒超时
      
      if (tempVideo) {
        tempVideo.onloadeddata = () => {
          clearTimeout(timeout);
          resolve();
        };
        
        tempVideo.onerror = (error) => {
          clearTimeout(timeout);
          reject(error);
        };
      }
    });
    
    // 关闭加载提示
    // loadingMessage.close();
    isLoadingCamera.value = false;
    // 关闭加载提示
    emit('loadingFalse', false,'');
    // 图像加载完成后，打开对话框
    cameraDialogVisible.value = true;
    
    // 等待DOM更新后设置视频源
    await nextTick();
    if (videoElement.value) {
      videoElement.value.srcObject = stream;
    }
  } catch (error) {
    //console.error('无法访问摄像头:', error);
    
    // 清理资源
    if (mediaStream.value) {
      mediaStream.value.getTracks().forEach((track) => track.stop());
      mediaStream.value = null;
    }
    emit('loadingFalse', false,'');
    isLoadingCamera.value = false;
    
    ElMessage({
      duration: 3000,
      message: '无法访问摄像头，请检查权限设置',
      type: 'error',
    });
  } finally {
    // 清理临时 video 元素
    if (tempVideo) {
      tempVideo.srcObject = null;
      tempVideo.remove();
      tempVideo = null;
    }
  }
};

/**
 * 关闭摄像头拍摄弹框
 */
const closeCameraDialog = () => {
  // 停止摄像头流
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach((track) => track.stop());
    mediaStream.value = null;
  }

  cameraDialogVisible.value = false;
};

// 拍摄照片
const capturePhoto = () => {
  if (!videoElement.value || !canvasElement.value) {
    ElMessage({
      message: '摄像头未准备就绪',
      type: 'error',
      duration: 2000,
    });
    return;
  }

  const video = videoElement.value;
  const canvas = canvasElement.value;
  const context = canvas.getContext('2d');

  if (!context) {
    ElMessage({
      message: '无法获取画布上下文',
      type: 'error',
      duration: 2000,
    });
    return;
  }

  // 设置画布尺寸与视频一致
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;

  // 绘制当前视频帧到画布
  context.drawImage(video, 0, 0, canvas.width, canvas.height);

  // 将画布内容转换为图片
  canvas.toBlob(
    (blob) => {
      if (!blob) {
        ElMessage({
          message: '拍摄失败',
          type: 'error',
          duration: 2000,
        });
        return;
      }

      const file = new File([blob], `capture_${Date.now()}.jpg`, {
        type: 'image/jpeg',
      });

      const reader = new FileReader();
      reader.onload = (e) => {
        base64Upload({
          baseStr: e.target?.result as string,
          isCompress: 'true',
        }).then((res) => {
          if (res.code === '200') {
            images.value.push({
              url: res.data,
              name: file.name,
              file: file,
            });
            updateModelValue();
            
            ElMessage.success('拍摄成功');
            
            // 延迟关闭弹窗，让用户看到成功提示
            setTimeout(() => {
              closeCameraDialog();
            }, 300);
          } else {
            //ElMessage.error(res.msg || '图片上传失败');
          }
        }).catch((error) => {
          //console.error('图片上传失败:', error);
          //ElMessage.error('图片上传失败');
        });
      };
      reader.readAsDataURL(file);
    },
    'image/jpeg',
    0.9
  );
};

/**
 * 智能拍摄对话框（优先高拍仪，无设备时使用电脑摄像头）
 */
const openSmartCaptureDialog = async () => {
  try {
    // 检查图片数量限制
    if (props.maxImages && images.value.length >= props.maxImages) {
      ElMessage.warning(`最多只能上传${props.maxImages}张图片`);
      return;
    }

    // HTTPS 环境说明：
    // 由于高拍仪服务通常不支持 HTTPS，我们配置为在 HTTPS 环境下强制使用 HTTP
    // 浏览器可能会显示混合内容警告，但功能可以正常使用
    // 如果遇到连接问题，请在浏览器设置中允许不安全内容
    emit('loadingFalse', true, '设备启动中...');
    // 优先使用缓存的连接状态，如果没有则重新检测
    let isConnected = scannerConnectionStatus.value;
    
    if (isConnected === null) {
      // 首次检测
      isConnected = await scanner.checkConnection();
      scannerConnectionStatus.value = isConnected;
    }
    
    if (isConnected) {
      // 有高拍仪设备，使用高拍仪
      try {
        await openScannerDialog();
      } catch (error: any) {
        //console.error('高拍仪启动失败，重新检测设备:', error);
        // 高拍仪启动失败，重新检测一次
        isConnected = await scanner.checkConnection();
        scannerConnectionStatus.value = isConnected;
        
        if (isConnected) {
          // 重试一次高拍仪
          try {
            await openScannerDialog();
          } catch (retryError: any) {
            //console.error('高拍仪重试失败，切换到摄像头:', retryError);
            // 重试失败，使用电脑摄像头
            ElMessage.warning('高拍仪连接失败，切换到电脑摄像头');
            await openCameraDialog();
          }
        } else {
          // 确认没有高拍仪，使用电脑摄像头
          await openCameraDialog();
        }
      }
    } else {
      // 没有高拍仪设备，使用电脑摄像头
      await openCameraDialog();
    }
  } catch (error: any) {
    //console.error('打开拍摄设备失败:', error);
    // 所有尝试失败，默认使用电脑摄像头
    ElMessage.warning('设备连接失败，尝试使用电脑摄像头');
    await openCameraDialog();
  }
};

/**
 * 打开高拍仪预览对话框（使用 WebSocket 视频流回调）
 */
const openScannerDialog = async () => {
  try {
    emit('loadingFalse', true, '设备启动中...');
    isLoadingScanner.value = true;
    
    // 打开视频流，并设置回调函数
    const success = await scanner.openVideoStream(0, (base64: string) => {
      // 每次收到新帧时更新图片
      scannerVideoUrl.value = `data:image/jpeg;base64,${base64}`;
      
      // 首次收到图像时关闭加载提示并显示对话框
      if (!scannerDialogVisible.value) {
        emit('loadingFalse', false, '');
        isLoadingScanner.value = false;
        scannerDialogVisible.value = true;
      }
    });

    if (!success) {
      throw new Error('无法打开高拍仪视频流');
    }
    
  } catch (error: any) {
    //console.error('打开高拍仪预览失败:', error);
    emit('loadingFalse', false, '');
    isLoadingScanner.value = false;
    throw error;
  }
};

/**
 * 关闭高拍仪预览对话框
 */
const closeScannerDialog = async () => {
  try {
    // 关闭对话框
    scannerDialogVisible.value = false;
    
    // 重置状态
    scannerCapturing.value = false;
    
    // 清空视频URL
    scannerVideoUrl.value = '';
    
    // 关闭视频流并断开连接
    await scanner.closeVideoStream(0);
  } catch (error) {
    //console.error('关闭高拍仪预览失败:', error);
    // 即使关闭失败也要清空状态
    scannerVideoUrl.value = '';
    scannerCapturing.value = false;
    scannerDialogVisible.value = false;
  }
};

/**
 * 处理对话框关闭事件（包括点击X或ESC）
 */
const handleScannerDialogClose = async () => {
  // 关闭对话框
  scannerDialogVisible.value = false;
  
  // 重置状态
  scannerCapturing.value = false;
  
  // 清空视频URL
  scannerVideoUrl.value = '';
  
  // 关闭视频流并断开连接
  await scanner.closeVideoStream(0);
};

/**
 * 在对话框中使用高拍仪拍摄
 */
const captureWithScannerDialog = async () => {
  try {
    // 设置拍摄中状态
    scannerCapturing.value = true;

    // 调用高拍仪拍摄（视频流已打开，保持连接）
    const result = await scanner.capture(0, false, true);

    if (result.success && result.imageData) {
      // 处理Base64图片数据
      let base64Data = result.imageData;
      
      // 确保包含data:image前缀
      if (!base64Data.startsWith('data:image')) {
        base64Data = `data:image/jpeg;base64,${base64Data}`;
      }

      // 上传到服务器
      const uploadResult = await base64Upload({
        baseStr: base64Data,
        isCompress: 'true',
      });

      if (uploadResult.code === '200' && uploadResult.data) {
        //console.log('高拍仪拍摄成功，上传结果:', uploadResult.data);
        // 添加到图片列表
        images.value.push({
          url: uploadResult.data,
          name: result.fileName || `scanner_${Date.now()}.jpg`,
          file: undefined,
        });
        
        updateModelValue();
        ElMessage.success('高拍仪拍摄成功');
        
        // 拍摄成功后关闭对话框
        setTimeout(() => {
          closeScannerDialog();
        }, 300);
      } else {
        //console.error('图片上传失败:', uploadResult);
        ElMessage.error(uploadResult.msg || '图片上传失败');
      }
    } else {
      //console.error('高拍仪拍摄失败:', result.error);
      ElMessage.error(result.error || '高拍仪拍摄失败');
    }
  } catch (error: any) {
    //console.error('高拍仪拍摄异常:', error);
    ElMessage.error(error.message || '高拍仪拍摄失败');
  } finally {
    // 恢复按钮状态
    scannerCapturing.value = false;
  }
};

// 更新模型值
const updateModelValue = () => {
  emit('update:modelValue', images.value);
  emit('change', images.value);

};

// 监听外部值变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      images.value = [...newValue];
    }
  },
  { deep: true }
);

/**
 * 初始化检测高拍仪连接状态（静默检测，不影响用户体验）
 */
const initScannerDetection = async () => {
  try {
    const isConnected = await scanner.checkConnection();
    scannerConnectionStatus.value = isConnected;
    
    // 仅在开发环境输出调试信息
    if (import.meta.env.DEV) {
      //console.log('[ImageUpload] 高拍仪设备状态:', isConnected ? '已连接' : '未连接');
    }
  } catch (error: any) {
    //console.error('[ImageUpload] 检测高拍仪连接失败:', error);
    scannerConnectionStatus.value = false;
  }
};

// 组件挂载时初始化
onMounted(() => {
  // 异步检测高拍仪连接状态，不阻塞页面加载
  initScannerDetection();
});

// 组件卸载时清理资源
onUnmounted(() => {
  if (mediaStream.value) {
    mediaStream.value.getTracks().forEach((track) => track.stop());
  }
});
</script>

<style scoped lang="scss">
.image-upload-container {
  width: 100%;
}

.image-display-area {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}

.image-list {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  flex: 1;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  background: #fafafa;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-overlay {
    position: absolute;
    top: 0px;
    right: 0px;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 0 0 0 6px;
    transition: opacity 0.3s ease;

    .delete-icon {
      color: white;
      font-size: 13px;
      cursor: pointer;
    }
  }
}

.upload-button-container {
  .upload-btn {
    display: flex;
    align-items: center;
    gap: 3px;
    padding: 6px 0;
    font-size: 14px;
    margin-left: 10px;
  }
}

// 摄像头拍摄弹框样式
.camera-dialog {
  .camera-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: #f5f5f5;
    border-radius: 8px;
  }

  .camera-preview {
    position: relative;
    width: 100%;
    max-width: 800px;
    background: #000;
    border-radius: 8px;
    overflow: hidden;
  }

  .camera-video {
    width: 100%;
    height: auto;
    display: block;
  }

  .camera-canvas {
    position: absolute;
    top: 0;
    left: 0;
  }

  .camera-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
    padding: 16px 0;

    .capture-btn {
      padding: 12px 32px;
      font-size: 16px;
      background: #16ada4;
      border-color: #16ada4;

      &:hover {
        background: #139a92;
        border-color: #139a92;
      }
    }
  }
}

// 高拍仪拍摄弹框样式
.scanner-dialog {
  .scanner-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: #f5f5f5;
    border-radius: 8px;
  }

  .scanner-preview {
    position: relative;
    width: 100%;
    max-width: 800px;
    background: #000;
    border-radius: 8px;
    overflow: hidden;
    min-height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .scanner-video {
    width: 100%;
    height: auto;
    display: block;
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    
    .el-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
    
    p {
      font-size: 16px;
      margin: 0;
    }
  }

  .scanner-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
    padding: 16px 0;

    .capture-btn {
      padding: 12px 32px;
      font-size: 16px;
      background: #16ada4;
      border-color: #16ada4;

      &:hover {
        background: #139a92;
        border-color: #139a92;
      }
      
      &:disabled,
      &.is-loading {
        background: #a0cfff;
        border-color: #a0cfff;
      }
    }
  }
}

// 下拉菜单样式
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-icon {
    font-size: 16px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .image-display-area {
    flex-direction: column;
  }

  .image-item {
    width: 100px;
    height: 100px;
  }

  .camera-dialog,
  .scanner-dialog {
    .camera-footer,
    .scanner-footer {
      flex-direction: column;
      align-items: center;

      .el-button {
        width: 120px;
      }
    }
  }
}
.image-overlay {
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  color: white;
}
</style>
